import { Breadcrumb, Card, Col, Row } from "antd"
import * as echarts from 'echarts'
import 'echarts/extension/bmap/bmap'
import { useEffect, useState } from "react"
import { Link, useLocation } from "react-router-dom"
import './index.scss'
import city from './sources/city'

import RightLayout from "./components/RightLayout"
import truck from './sources/truck'


const roadColor = ['#fa541c', '#722ed1', '#2f54eb', '#52c41a', '#000000', '#fa8c16', '#eb2f96', '#f5222d', '#faad14', '#1677ff', '#ffec3d', '#a0d911', '#13c2c2', '#B22222', '#BA55D3', '#BDB76B', '#FFA07A', '#66CDAA', '#556B2F', '#0000CD']


const Show = () => {
  const location = useLocation()
  const data = location.state ? location.state.data : null// 访问传递的数据
  const info = location.state ? location.state.info : null// 访问传递的数据

  const path_data = []
  let cust_num = 1
  if (data) {
    for (let i = 0;i < data.length;i++) {
      const p = data[i]
      cust_num += data[i].length - 2
      const path_obj = []
      for (let j = 0;j < p.length;j++) {
        const cust_index = p[j]
        const cust = city[cust_index]
        path_obj.push({
          "name": cust.name,
          "value": [cust.longitude, cust.latitude]
        })
      }
      path_data.push(path_obj)
    }
  }


  const [myChart, setMyChart] = useState(null) // 存储echarts实例
  const [selectedPath, setSelectedPath] = useState({})
  const [pointColor, setPointColor] = useState([])


  function getRandomColor () {
    // 生成深色系
    const r = Math.floor(Math.random() * 192)
    const g = Math.floor(Math.random() * 192)
    const b = Math.floor(Math.random() * 192)
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
  }
  const color = []
  if (pointColor.length === 0) {
    for (let i = 0;i < cust_num;i++) {
      color.push(getRandomColor())
    }
    setPointColor(color)
  }

  useEffect(() => {
    var myCharts = echarts.init(document.getElementById('container'))
    setMyChart(myCharts)
    // React脚手架中全局变量都要用window去访问
    const BMap = window.BMap //这样写也可以
    // const { BMap } = window
    // // 初始化地图实例


    var startPoint = {  //页面初始化坐标点(长沙)
      x: 112.982279,
      y: 28.19409
    }

    // 地图自定义样式
    var bmap = {
      center: [startPoint.x, startPoint.y], // 地图的中心点坐标
      zoom: 6, // 地图的缩放级别
      roam: true, // 启用缩放和漫游
      mapOptions: { enableMapClick: false },//底图是否可以点击
    }

    const path_data = []
    let cust_num = 1
    if (data) {
      for (let i = 0;i < data.length;i++) {
        const p = data[i]
        cust_num += data[i].length - 2
        const path_obj = []
        for (let j = 0;j < p.length;j++) {
          const cust_index = p[j]
          const cust = city[cust_index]
          path_obj.push({
            "name": cust.name,
            "value": [cust.longitude, cust.latitude]
          })
        }
        path_data.push(path_obj)
      }
    }



    const city_data = []
    for (let i = 0;i < city.length;i++) {
      const c = city[i]
      if (i === cust_num) {
        break
      }
      city_data.push({
        name: c.name,
        value: [c.longitude, c.latitude],
        itemStyle: {
          color: pointColor[i] // 为每个城市指定一个随机颜色
        }
      })
    }

    const seriesOption = {
      name: '效果点',
      type: 'effectScatter',
      coordinateSystem: 'bmap',
      symbolSize: 10,
      zlevel: 3,
      showEffectOn: 'render',
      data: city_data,
    }

    // 中心点长沙
    const seriesOption2 = {
      name: '效果点',
      type: 'effectScatter',
      coordinateSystem: 'bmap',
      symbolSize: 15,
      zlevel: 4,
      showEffectOn: 'render',
      data: [
        {
          "name": "长沙市",
          "value": [112.982279, 28.19409]
        }
      ],
      itemStyle: {
        normal: {
          color: 'red' // 这里设置的是默认颜色，现在会被data中的颜色覆盖
        }
      },
    }

    function calculateDistance (coord1, coord2) {
      // 计算两点间的直线距离
      return Math.sqrt(Math.pow(coord1[0] - coord2[0], 2) + Math.pow(coord1[1] - coord2[1], 2))
    }

    let roadColorIndex = 0
    function generateSeriesConfig (cities, constantSpeed = 100) {
      let seriesData = []
      let totalDelay = 0
      let lineColor = roadColor[roadColorIndex++ % roadColor.length]
      for (let i = 0;i < cities.length;i++) {
        if (i === cust_num) {
          break
        }
        const city = cities[i]
        const currentCity = city.value
        const nextCity = cities[(i + 1) % cities.length].value
        const distance = calculateDistance(currentCity, nextCity)
        const time = (distance / constantSpeed) * 1000
        seriesData.push({
          name: `路径${roadColorIndex}`,
          coordinateSystem: 'bmap',
          type: 'lines',
          zlevel: 2,
          effect: {
            show: true,
            delay: totalDelay * 1000, // Accumulative delay
            period: time / 10, // Time in seconds for the effect to traverse from start to end
            trailLength: 0,
            symbol: truck,
            symbolSize: 12,
            loop: false,
          },
          lineStyle: {//线的样式设置
            type: roadColorIndex < 20 ? 'solid' : roadColorIndex < 40 ? 'dotted' : roadColorIndex < 60 ? 'dotted' : roadColorIndex < 80 ? [2, 4] : [2, 6],
            opacity: 1,
            width: 2.0,
            color: lineColor,
          },
          data: [{
            fromName: `${city.name}`, toName: `${cities[(i + 1) % cities.length].name}`,
            coords: [currentCity, nextCity]
          }]

        })
        totalDelay += time / 10
      }
      return seriesData
    }

    const series = []
    series.push(seriesOption)
    series.push(seriesOption2)

    // console.log(path_data)

    for (let path of path_data) {
      const seriesConfig = generateSeriesConfig(path, 500)
      for (const config of seriesConfig) {
        series.push(config)
      }
    }

    const option = {
      title: {
        text: '',
        left: 'center',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'vertical', // 图例列表的布局朝向，'vertical'表示垂直排列
        type: 'scroll',
        left: 'left', // 图例组件离容器左侧的距离
        top: 'top', // 图例组件离容器底部的距离
        botttom: 20,
        zlevel: 100,
        data: path_data.map((path, index) => {
          return {
            name: `路径${index + 1}`,
            icon: index < 20 ? 'roundRect' : index < 40 ? 'circle' : index < 60 ? 'triangle' : index < 80 ? 'diamond' : 'arrow'
          }
        }), // 使用路径名称作为图例项
        textStyle: {
          color: 'inherit' // 图例文字的颜色
        },
        selected: selectedPath
      },
      bmap,
      series
    }


    myCharts.setOption(option)

    var bdmap = myCharts.getModel().getComponent('bmap').getBMap()
    // var pt = new BMap.Point(116.417, 39.909)
    // var markerTem = new BMap.Marker(pt) // 创建标注
    // bdmap.addOverlay(markerTem) // 将标注添加到地图中
    // bdmap.enableScrollWheelZoom(true)
    // bdmap.enableScrollWheelZoom(true);

    // const map = new BMap.Map("container")
    // map.enableScrollWheelZoom(true)
    // var myCustomControl = new CustomControl()
    // bdmap.addControl(myCustomControl)


    bdmap.addControl(new BMap.NavigationControl({
      // eslint-disable-next-line no-undef
      anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
    }))               // 添加平移缩放控件
    bdmap.addControl(new BMap.ScaleControl())                    // 添加比例尺控件
    bdmap.enableContinuousZoom()                              //启用地图惯性拖拽，默认禁用
    // bdmap.addControl(new BMap.OverviewMapControl())              //添加缩略地图控件
    // bdmap.enableScrollWheelZoom()                            //启用滚轮放大缩小
    bdmap.addControl(new BMap.MapTypeControl())          //添加地图类型控件
    // bdmap.disable3DBuilding()
    // bdmap.setMapStyle({ style: 'normal' })          //设置模板的初始风格
    //地图监听事件
    // bdmap.addEventListener("click", function (e) {
    //   console.log(e.point.lng + "," + e.point.lat)
    // })

    myCharts.on('legendselectchanged', function (event) {
      const selectedPath = event.name
      const series = option.series.map(s => ({
        ...s,
        // 只显示选中的路径系列，其他路径系列隐藏
        show: s.name === selectedPath
      }))

      myCharts.setOption({
        series: series
      })
    })


  }, [selectedPath])


  const handelClickPath = (pathName) => {
    if (!myChart) return
    if (pathName) {
      const obj = {}
      for (let i = 1;i <= path_data.length;i++) {
        const key = `路径${i}`
        obj[key] = false
      }
      obj[pathName] = true
      setSelectedPath(obj)
    } else {
      const obj = {}
      for (let i = 1;i <= path_data.length;i++) {
        const key = `路径${i}`
        obj[key] = true
      }
      setSelectedPath(obj)
    }
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '路径可视化' },
          ]}
            className='breadcrumb'
          />
        }
      >
        <Row>
          <Col span={17}>
            <div className="map">
              {/* 地图容器元素 */}
              <div id="container" style={{ width: '100%', height: '70vh' }} />
            </div>
          </Col>
          <Col span={6} offset={1}>
            <RightLayout
              info={info}
              path_data={path_data}
              handelClickPath={handelClickPath}
            />
          </Col>
        </Row>

      </Card>
    </div>
  )
}

export default Show